#include "secondwindow.h"
#include "ui_secondwindow.h"
#include <QPushButton>
#include <QCloseEvent>
#include <QNetworkRequest>
#include <QUrl>
#include <QFile>
#include <QDir>
#include <QStandardPaths>
#include <QMessageBox>
#include <QProgressBar>
#include <QLineEdit>
#include <QFileDialog>
#include <QImage>
#include <QPixmap>

SecondWindow::SecondWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SecondWindow),
    m_networkManager(new QNetworkAccessManager(this)),
    m_currentReply(nullptr)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_QuitOnClose, false);

    // 初始化进度条
    ui->progressBar->setRange(0, 100);
    ui->progressBar->setValue(0);
    ui->progressBar->setVisible(false); // 初始隐藏

    // 连接返回按钮
    connect(ui->backButton, &QPushButton::clicked, this, [this]() {
        emit backRequested();
        this->hide();
    });

    // 连接下载按钮
    connect(ui->downloadButton, &QPushButton::clicked, this, &SecondWindow::startDownload);

    // 网络完成信号
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &SecondWindow::onDownloadFinished);
}

SecondWindow::~SecondWindow()
{
    delete ui;
}

void SecondWindow::startDownload()
{
    QString urlStr = ui->urlLineEdit->text().trimmed();
    if (urlStr.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请输入图片 URL！");
        return;
    }

    QUrl url(urlStr);
    if (!url.isValid() || (url.scheme() != "http" && url.scheme() != "https")) {
        QMessageBox::warning(this, "URL 无效", "请输入有效的 HTTP/HTTPS 链接。");
        return;
    }

    // 显示进度条
    ui->progressBar->setVisible(true);
    ui->progressBar->setValue(0);

    // 发起请求
    QNetworkRequest request(url);
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    request.setHeader(QNetworkRequest::UserAgentHeader, "MyQtApp/1.0");

    m_currentReply = m_networkManager->get(request);

    // 连接进度信号（必须在 get() 之后连接，否则可能错过早期信号）
    connect(m_currentReply, &QNetworkReply::downloadProgress,
            this, &SecondWindow::onDownloadProgress);
}

void SecondWindow::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if (bytesTotal > 0) {
        int percent = static_cast<int>(100 * bytesReceived / bytesTotal);
        ui->progressBar->setValue(percent);
    } else {
        // 未知总大小：可显示为“正在下载...”或使用不确定进度条
        // 这里简单处理：不更新进度值，保持 0
    }
}

void SecondWindow::onDownloadFinished(QNetworkReply *reply)
{
    // 断开进度信号（避免多次触发）
    disconnect(reply, &QNetworkReply::downloadProgress, this, nullptr);

    ui->progressBar->setVisible(false);

    if (reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "下载失败",
            QString("错误代码 %1:\n%2")
            .arg(reply->error())
            .arg(reply->errorString()));
        reply->deleteLater();
        return;
    }

    QByteArray imageData = reply->readAll();
    if (imageData.isEmpty()) {
        QMessageBox::warning(this, "下载失败", "接收到的数据为空。");
        reply->deleteLater();
        return;
    }

    saveImage(imageData);
    reply->deleteLater();
}

void SecondWindow::saveImage(const QByteArray &data)
{
    // 获取原始 URL 用于建议文件名
    QString urlStr = ui->urlLineEdit->text().trimmed();
    QString baseName = QUrl(urlStr).fileName();
    if (baseName.isEmpty() || !baseName.contains('.')) {
        baseName = "downloaded_image.jpg";
    }

    // 弹出“另存为”对话框
    QString filePath = QFileDialog::getSaveFileName(
        this,
        tr("保存图片"),
        QDir::home().filePath(baseName), // 默认路径 + 建议文件名
        tr("Images (*.png *.jpg *.jpeg *.bmp *.gif);;All Files (*)")
    );

    if (filePath.isEmpty()) {
        // 用户取消保存
        showImagePreview(data); // 仍可预览
        return;
    }

    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(data);
        file.close();
        QMessageBox::information(this, "成功", QString("图片已保存至：\n%1").arg(filePath));
        showImagePreview(data);
    } else {
        QMessageBox::critical(this, "保存失败", "无法写入文件。");
        showImagePreview(data); // 即使保存失败也预览
    }
}

void SecondWindow::showImagePreview(const QByteArray &data)
{
    QImage image;
    if (image.loadFromData(data)) {
        QPixmap pixmap = QPixmap::fromImage(image);
        // 自动缩放以适应 QLabel，保持宽高比
        ui->previewLabel->setPixmap(pixmap.scaled(
            ui->previewLabel->size(),
            Qt::KeepAspectRatio,
            Qt::SmoothTransformation
        ));
    } else {
        ui->previewLabel->setText("无法加载图片预览");
    }
}

void SecondWindow::closeEvent(QCloseEvent *event)
{
    event->ignore();
    emit backRequested();
    this->hide();
}

//定时器
void SecondWindow::on_timerBt_clicked()
{
    if (m_timer) {
        m_timer->deleteLater(); // 安全删除
        m_timer = nullptr;
    }

    if (!m_timer) {
        m_timer = new timer(nullptr); // ← parent = nullptr！独立窗口
        connect(m_timer, &timer::backRequested, this, [this]() {
            this->show();  // 重新显示主窗口
        });
    }
    m_timer->show();
    this->hide();
}
